package com.xsir.util;

import com.wxapi.WxApiCall.WxApiCall;
import com.wxapi.model.RequestModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author user
 * @date 2020/8/31
 */
@Component
public class Util {
    private static final Logger log = LoggerFactory.getLogger(Util.class);
    
    private static JavaMailSender sender;
    
    private static String from;
    
    @Resource
    private JavaMailSender mailSender;
    
    @Value("${mail.from}")
    public void setFrom(String f) {
        from = f;
    }
    
    @PostConstruct
    private void init() {
        sender = mailSender;
    }
    
    
    /**
     * 验证手机号的正则表达式
     */
    public static final String REGEX_PHONE = "^1[3456789]\\d{9}$";
    /**
     * 验证邮箱的正则表达式
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    
    /**
     * 随机生成指定位数的数字串
     *
     * @param len 位数
     * @return 数字串，当len <= 0时，返回”0“
     */
    public static String randomCode(Integer len) {
        if (len <= 0) {
            return "0";
        }
        
        int[] number = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        
        for (int i = 0; i < len; i++) {
            int index = random.nextInt(10000);
            code.append(number[index % number.length]);
        }
        
        return code.toString();
    }
    
    /**
     * 发送邮件
     *
     * @param to      收件人地址
     * @param subject 主题
     * @param content 内容
     */
    public static Boolean sendSimpleMail(String to, String subject, String content) {
        
        log.info("\n\n" + sender.toString() + "\n\n");
        
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        
        try {
            sender.send(message);
            return true;
        } catch (MailException e) {
            log.error(e.getMessage());
            return false;
        }
    }
    
    /**
     * 调用万象API获取新闻
     * @param channel   频道
     * @param num       新闻条数
     * @param start     起始编号
     * @return          json字符串
     */
    public static String getNews(String channel, Integer num, Integer start) {
        RequestModel model = new RequestModel();
        model.setGwUrl("https://way.jd.com/jisuapi/get");
        model.setAppkey("51716dbffdc1f9db463e4dd452539638");
        Map<String, Object> queryMap = new HashMap<>(4);
        queryMap.put("channel",channel); //访问参数
        queryMap.put("num",num); //访问参数
        queryMap.put("start",start); //访问参数
        model.setQueryParams(queryMap);
        WxApiCall call = new WxApiCall();
        call.setModel(model);
        String result = call.request();
        // 获取到json字符串之后，理应判断响应码code是否正确
        return result.substring(result.indexOf("["), result.lastIndexOf("]") + 1);
    }
}
